package com.zenithmind.chat.config;

import com.zenithmind.chat.pojo.entity.ModelConfig;
import com.zenithmind.chat.service.ModelConfigService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import jakarta.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Data
@Configuration
@ConfigurationProperties(prefix = "ai")
public class AiConfig {

    @Autowired(required = false)
    private ModelConfigService modelConfigService;

    private OpenAiConfig openAi = new OpenAiConfig();
    private OllamaConfig ollama = new OllamaConfig();
    
    // 缓存所有启用的模型配置
    private Map<String, ModelConfig> modelConfigCache = new ConcurrentHashMap<>();
    
    // 定时任务执行器
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    
    @Data
    public static class OpenAiConfig {
        /**
         * OpenAI API 密钥
         */
        private String apiKey;
        
        /**
         * OpenAI API 地址
         */
        private String apiUrl = "https://api.openai.com/v1/chat/completions";
        
        /**
         * 默认模型
         */
        private String defaultModel = "gpt-3.5-turbo";
    }
    
    @Data
    public static class OllamaConfig {
        /**
         * Ollama API 地址
         */
        private String apiUrl = "http://localhost:11434";
        
        /**
         * 默认模型
         */
        private String defaultModel = "qwen3:8b";
    }
    
    /**
     * AI服务专用RestTemplate
     */
    @Bean("aiRestTemplate")
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder
            .defaultMessageConverters() // 使用默认的消息转换器
            .additionalInterceptors((request, body, execution) -> {
                request.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
                return execution.execute(request, body);
            })
            .build();
    }
    
    /**
     * 初始化配置，从数据库加载模型配置并设置定时刷新
     */
    @PostConstruct
    public void init() {
        // 首次加载配置
        refreshModelConfigs();
        
        // 设置定时任务，每5分钟刷新一次配置
        scheduler.scheduleAtFixedRate(
            this::refreshModelConfigs, 
            5, 
            5, 
            TimeUnit.MINUTES
        );
    }
    
    /**
     * 从数据库刷新模型配置
     */
    public void refreshModelConfigs() {
        if (modelConfigService == null) {
            return;
        }
        
        try {
            List<ModelConfig> configs = modelConfigService.getAllEnabledModels();
            
            // 清空缓存并重新加载
            modelConfigCache.clear();
            
            // 将配置加入缓存，键格式为 "类型:名称"
            for (ModelConfig config : configs) {
                String key = config.getModelType() + ":" + config.getModelName();
                modelConfigCache.put(key, config);
                
                // 更新默认配置
                updateDefaultConfig(config);
            }
        } catch (Exception e) {
            // 加载失败时使用默认配置
            // 日志记录错误但不影响应用启动
            e.printStackTrace();
        }
    }
    
    /**
     * 根据配置更新默认值
     */
    private void updateDefaultConfig(ModelConfig config) {
        try {
            if (config.getModelType() == 1) { // OpenAI
                if (config.getApiUrl() != null && !config.getApiUrl().isEmpty()) {
                    openAi.setApiUrl(config.getApiUrl());
                }
                if (config.getApiKey() != null && !config.getApiKey().isEmpty()) {
                    openAi.setApiKey(config.getApiKey());
                }
            } else if (config.getModelType() == 2) { // Ollama
                if (config.getApiUrl() != null && !config.getApiUrl().isEmpty()) {
                    ollama.setApiUrl(config.getApiUrl());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取模型配置
     * @param modelType 模型类型
     * @param modelName 模型名称
     * @return 模型配置
     */
    public ModelConfig getModelConfig(Integer modelType, String modelName) {
        String key = modelType + ":" + modelName;
        return modelConfigCache.get(key);
    }
} 